<?php
class DBData 
{
	public static $tableName;
	public static $dbw=NULL;
	public static $dbr=NULL;
	public static $globalSqlDebug=0;
	public static $dbconfig=NULL;
	public static $tablepre = "lzh_";
	public static $print = '';
	public static $onlytxt = 0;  ///针对setSqlDebug的时候，这个值为1的时候，那么就只生成文件不打印文件
	public static function setconfig()
	{
		if(empty(self::$dbconfig))
		{
			$config['db'] = include_once ROOT."/db/db.php";
			self::$dbconfig = $config['db'];  
		}
	}
	public static function settableName($tablename)
	{
		self::$tableName = $tablename;
	}
	public static function setonlytxt($tf=1)
	{
		self::$onlytxt = $tf;
	}
	public static function printSql($tf="printsql")
	{
			self::$print = $tf;
	}
	public static function setSqlDebug($tf=1)
	{
		self::$globalSqlDebug=$tf;
	}
	public static function setdbw()
	{
		self::setconfig();
		
		if(empty(self::$dbw))
		{
			self::setconfig();
			
			$host = self::$dbconfig['writedb']['host'];
			$dbname = self::$dbconfig['writedb']['dbname'];
			$dbuser = self::$dbconfig['writedb']['dbuser'];
			$dbpwd = self::$dbconfig['writedb']['dbpwd'];
			self::$dbw = new PDO("mysql:host=$host;dbname=$dbname","$dbuser","$dbpwd");
			self::$dbw->exec("SET NAMES 'utf8';"); 
		}
	}
	public static function setdbr()
	{
		
		if(empty(self::$dbr))
		{
			self::setconfig();
			//var_dump(self::$dbconfig); exit();
			$host = self::$dbconfig['readdb']['host'];
			$dbname = self::$dbconfig['readdb']['dbname'];
			$dbuser = self::$dbconfig['readdb']['dbuser'];
			$dbpwd = self::$dbconfig['readdb']['dbpwd'];
			self::$dbr = new PDO("mysql:host=$host;dbname=$dbname","$dbuser","$dbpwd");
			self::$dbr->exec("SET NAMES 'utf8';");  
		}
	}
        
	public static function printtxt($sql,$folder='log')
	{
		$filename = ROOT."/log/{$folder}_".date("Ymd").".log";
		file_put_contents($filename,date("Y-m-d H:i:s")."\t".$sql.";\n",FILE_APPEND);
	}
	public static function execsql($sql,$returnid=0,$isend=1)
	{
		self::setdbw();
		if(self::$globalSqlDebug)
		{
                    echo "<br>"; echo $sql; echo ";<br>\r\n";
		}
		if(self::$print)
		{
//			$filename = ROOT."/log/".date("Ymd")."_printsql_".self::$print.".txt";
                        self::printtxt($sql, self::$print);
		}
		$tf=self::$dbw->exec($sql); 
                if(!is_numeric($tf))
                {
                    $errArr = self::$dbw->errorInfo();
                    $errjson = "有错误";
                    if(is_array($errArr))
                    {
                        $errjson = json_encode($errArr);
                    }elseif(is_string($errArr))
                    {
                        $errjson = $errArr;
                    }
//                        $filename = ROOT."/log/".date("Ymd")."_err_sql.log";   
                    //file_put_contents($filename,date("Y-m-d H:i:s")."\t".$sql."\t".$errjson.";\n",FILE_APPEND);
                    self::errline($sql."\t".$errjson,"err_sql");
                }
                
//		if(!$tf)
//		{
//                    $errArr = self::$dbw->errorInfo();
//                    $errjson = "有错误";
//                    if(is_array($errArr))
//                    {
//                        $errjson = json_encode($errArr);
//                    }elseif(is_string($errArr))
//                    {
//                        $errjson = $errArr;
//                    }
////                        $filename = ROOT."/log/".date("Ymd")."_err_sql.log";   
//                    //file_put_contents($filename,date("Y-m-d H:i:s")."\t".$sql."\t".$errjson.";\n",FILE_APPEND);
//                    self::errline($sql."\t".$errjson,"err_sql2");
//		}
                
		if(self::$globalSqlDebug)
		{
			if(!$tf)
			{
				self::$dbw->errorInfo();
			}
		}
		if($returnid == 1)
		{
			//insert操作
			return $id=self::$dbw->lastInsertId();
		}else
		{
			return $tf;
		}
	}
	///处理数组条件
	public static function initwhere($where)
	{
		$_whe="";
		if(!is_array($where))
		{
			if(strlen($where) > 0)
			{
				$_whe = ' where '.$where;
			}
			
		}  else {
			///where 一维数组
			$newArr = array();
			foreach($where as $fields => $value)
			{
				if(!empty($_whe))
				{
					$_whe .= ' and ';
				}
				if(is_numeric($fields))
				{
					$_whe .=  $value  ;
				}else
				{
					
					$_whe .= " $fields = '".$value."' ";
				}
			}
							
			if(!empty($_whe))
			{
				$_whe = ' where '.$_whe; 
			}
			
		}
		return $_whe;
	}
	//返回单条语句
	public static function getRecord($fields='*', $where='', $extra='',$tab='')
	{
		$sql = self::getsql($fields, $where, $extra, 0,1,$tab);
		return self::selectsql($sql,"row");		
	}
    public static function Record($fields='*', $where='',$tab='', $extra='')
	{
		$sql = self::getsql($fields, $where, $extra, 0,1,$tab);
		return self::selectsql($sql,"row");		
	}
	//返回多条语句
	public static function getRecordList($fields='*', $where='', $extra='',$tab="")
	{
		if(!empty($tab))
		{
			self::$tableName = $tab;
		}
		$sql = self::getsql($fields, $where, $extra);
		return self::selectsql($sql,"list");
	}
    public static function RecordList($fields='*', $where='',$tab="", $extra='',$page=0,$pagesizes=0)
	{
        $sql = self::getsql($fields,$where,$extra,$page,$pagesizes,$tab);
		return self::selectsql($sql, "list");
	}
	public static function RecordListSql($fields='*', $where='',$tab="", $extra='',$page=0,$pagesizes=0)
	{
        $sql = self::getsql($fields,$where,$extra,$page,$pagesizes,$tab);
		return $sql;
	}
	
	public static function select($sql)
	{
		return self::selectsql($sql,"row");
	}
	public static function selectlist($sql)
	{
		return self::selectsql($sql,"list");
	}
	public static function selectsql($sql,$l)
	{
		self::setdbr();
		if(self::$globalSqlDebug)
		{
			if(self::$onlytxt==0)
			{
				echo "<br>"; echo $sql; echo ";<br>\r\n";
			}
			 
		}
                if(self::$print)
                {
//                    $filename = ROOT."/log/".date("Ymd")."_printsql_".self::$print.".txt";
//                    file_put_contents($filename,date("Y-m-d H:i:s")."\t".$sql.";\n",FILE_APPEND);
                    self::printtxt($sql, self::$print);
                }
                $rs=self::$dbr->query($sql) ;
		if($rs)
		{
			$backall=NULL;
			$rs->setFetchMode(PDO::FETCH_ASSOC); //设置关联模式
			if($l=="row")
			{
				$arr=$rs->fetch();
				$backall=$arr;
			}else
			{
				$arrlist=$rs->fetchAll();
				$backall=$arrlist;
			}
			return $backall;				
		}else
		{
                    
                    
			$errArr = self::$dbr->errorInfo();
			$errjson = json_encode($errArr);

//                        $filename = ROOT."/log/".date("Ymd")."_err_sql.log";   
//                        file_put_contents($filename,date("Y-m-d H:i:s")."\t".$sql."\t".$errjson.";\n",FILE_APPEND);
                        self::errline($sql."\t".$errjson);
                       
			if(self::$globalSqlDebug)
			{
				if(self::$onlytxt==0)
				{
					echo "<br>"; echo $sql; echo ";<br>\r\n";
				}
				 
				print_r(self::$dbr->errorInfo()); 
			}else
			{
				print_r(self::$dbr->errorInfo()); 
				exit();
			}
		}
	}
        public static function errline($str,$logname="err_sql")
        {
            $errArr = debug_backtrace();
            $file = $errArr[2]['file'];
            $line = $errArr[2]['line'];
            $txt = $str."\t".$file."\t".":".$line;
            self::printtxt($txt, $logname);
        }
	
	///获取一个表的所有字段
	public static function getFields($tab)
	{
		$sql="show columns from ".$tab;
		$arrList = self::selectlist($sql);
		$fieldsArr = [];
		foreach($arrList as $arr)
		{ 
			$fieldsArr[$arr['Field']] = $arr['Default'];
		}
		return $fieldsArr;
	}
	public static function inserttable( $data,$returnid=0,$tab="") 
	{
		$sql = '';
		$tablename = self::$tableName;
		if(!empty($tab))
		{
			$tablename = $tab;
		}
		if (!empty($data) && is_array($data)) {
			$sql = "INSERT INTO ".$tablename." SET ";
			$comma = '';
			foreach ($data as $key => $val) {
				if (strlen($val) > 0) {
					$sql .= $comma . '`' . $key . "`='" . $val . "'";
					$comma = ',';
				}
			}
		}
		return self::execsql($sql,$returnid);
	}
        public static function intotable( $data,$tab="",$returnid=0) 
	{
		$sql = '';
		if(!empty($tab))
		{
                    if(is_string($tab))
                    {
                        $tablename = $tab;
                    }else
                    {
                        $tablename = $tab->tablename;
                    }
		}else
                {
                    $tablename = self::$tableName;
                }
		if (!empty($data) && is_array($data)) {
			$sql = "INSERT INTO ".$tablename." SET ";
			$comma = '';
			foreach ($data as $key => $val) {
				if (strlen($val) > 0) {
					$sql .= $comma . '`' . $key . "`='" . $val . "'";
					$comma = ',';
				}
			}
		}
		return self::execsql($sql,$returnid);
	}
    public static function intosql( $data,$tab="") 
	{
		$sql = ''; 
		if(!empty($tab))
		{
                    if(is_string($tab))
                    {
                        $tablename = $tab;
                    }else
                    {
                        $tablename = $tab->tablename;
                    }
		}else
                {
                    $tablename = self::$tableName;
                }
		if (!empty($data) && is_array($data)) {
			$sql = "INSERT INTO ".$tablename." SET ";
			$comma = '';
			foreach ($data as $key => $val) {
				if (strlen($val) > 0) {
					$sql .= $comma . '`' . $key . "`='" . $val . "'";
					$comma = ',';
				}
			}
		}
		return $sql;
	}
        
	public static function updatetable( $data, $where, $act = "",$tab="",$isbacknum = 0) 
	{
		$where = self::initwhere($where);
		$table = self::$tableName;
		if(!empty($tab))
		{
			$table = $tab;
		}
		$sql = '';
		if (!empty($data)) 
		{
			$sql = "update ".$table." SET ";
			if(is_array($data))
			{
				$comma = '';
				foreach ($data as $key => $val) 
				{
					if ($act == "") 
					{
						if (strlen($val) > 0) 
						{
							$sql .= $comma . '`' . $key . "`='" . $val . "'";
							$comma = ',';
						}
					} else {
						if (strlen($val) > 0) 
						{
							$sql .= $comma . '`' . $key . "`='" . $val . "'";
						} else 
						{
							$sql .= $comma . '`' . $key . "`=NULL";
						}
						$comma = ',';
					}
				}
				$sql.=" $where";
			}else
			{
				$sql.=$data." ".$where;
			}
                        
                        if($isbacknum == 0 || $isbacknum==2)
                        {

                        }else
                        {
                                $isbacknum = 0;
                        }
                        $tf = self::execsql($sql,$isbacknum);
                        return $tf;
				
		}
		
	}
    public static function uptable( $data, $where, $tab, $act = "") 
	{
		$where = self::initwhere($where); 
		
        if(!empty($tab))
		{
                    if(is_string($tab))
                    {
                        $table = $tab;
                    }else
                    {
                        $table = $tab->tablename;
                    }
		}else
                {
                    $table = self::$tableName;
                }
		$sql = '';
		if (!empty($data)) 
		{
			if(is_array($data))
			{
				$comma = '';
				foreach ($data as $key => $val) 
				{
					if(is_numeric($key))
					{
							$sql .= $comma . $val;
							$comma = ',';
					}else
					{
						if ($act == "") 
						{
							if (strlen($val) > 0) 
							{
								$sql .= $comma . '`' . $key . "`='" . $val . "'";
								$comma = ',';
							}
						} else {
							if (strlen($val) > 0) 
							{
								$sql .= $comma . '`' . $key . "`='" . $val . "'";
							} else 
							{
								$sql .= $comma . '`' . $key . "`=NULL";
							}
							$comma = ',';
						}
                    }
				}
			}else
			{
				$sql = $data;
			}    
			if(empty($sql))
			{
				if(is_array($data))
				{
					$data = json_encode($data,256);
				}
				self::printtxt($data.'：更新'.$tab.'表语句为空',"err_sql2");
				return false;
			}else
			{
				$sql = 'update '.$table.' set '.$sql.$where;         
				$tf = self::execsql($sql);
				return $tf;
			}
		}
	}
    public static function upsql( $data, $where, $tab, $act = "") 
	{
		$where = self::initwhere($where); 
		
        if(!empty($tab))
		{
                    if(is_string($tab))
                    {
                        $table = $tab;
                    }else
                    {
                        $table = $tab->tablename;
                    }
		}else
                {
                    $table = self::$tableName;
                }
		$sql = '';
		if (!empty($data)) 
		{
			if(is_array($data))
			{
				$comma = '';
				foreach ($data as $key => $val) 
				{
					if(is_numeric($key))
					{
							$sql .= $comma . $val;
							$comma = ',';
					}else
					{
						if ($act == "") 
						{
							if (strlen($val) > 0) 
							{
								$sql .= $comma . '`' . $key . "`='" . $val . "'";
								$comma = ',';
							}
						} else {
							if (strlen($val) > 0) 
							{
								$sql .= $comma . '`' . $key . "`='" . $val . "'";
							} else 
							{
								$sql .= $comma . '`' . $key . "`=NULL";
							}
							$comma = ',';
						}
                    }
				}
			}else
			{
				$sql = $data;
			}    
			if(empty($sql))
			{
				return 'sql更新为空';
			}else
			{
				$sql = 'update '.$table.' set '.$sql.$where;         
				return $sql;
			}
		}
		
	}
	public static function deltable($where,$tab='',$returnid=0)
	{
		
		if(!empty($tab))
		{
			if(is_string($tab))
			{
				$table = $tab;
			}else
			{
				$table = $tab->tablename;
			}
		}else
		{
			$table = self::$tableName;
		}
		$where = self::initwhere($where);
		$sql = "delete from ".$table." $where ";
		return self::execsql($sql,$returnid);
	}
    public static function delsql($where,$tab='')
	{
		$table = self::$tableName;
		if(!empty($tab))
		{
			if(is_string($tab))
			{
				$table = $tab;
			}else
			{
				$table = $tab->tablename;
			}
		}
		$where = self::initwhere($where);
		$sql = "delete from ".$table." $where ";
		return $sql;
	}
	public static function getsql($fields,$where,$extra,$page=0,$pagesizes=0,$tab="")
	{
		$where = self::initwhere($where);
		if(!empty($tab))
		{
			if(is_string($tab))
			{
				$tablename = $tab;
			}else
			{
				$tablename = $tab->tablename;
			}
		}else
		{
			$tablename = self::$tableName;
		}
		$sql="select $fields from ".$tablename." $where $extra ";
		if(empty($page))
		{
			$page = 1;
		}
		if($pagesizes>0)
		{
			$page=$page-1;
			if($page<0)
			{
				$page=0;
			}
			$s=$page*$pagesizes;
			$sql.=" limit $s,$pagesizes";
		}
		return $sql;
	}
	public static function getCount($where='',$tab='')
	{
		
                if(!empty($tab))
		{
                    if(is_string($tab))
                    {
                        $table = $tab;
                    }else
                    {
                        $table = $tab->tablename;
                    }
		}else
                {
                    $table = self::$tableName;
                }
                
                
		if(!empty($tab))
		{
			$table = $tab;
		}
		$total = 0;
		$where = self::initwhere($where);
		$sql = "select count(*) as total from ".$table ." ". $where;
		
		$arr = self::selectsql($sql, "row");
		if($arr)
		{
			$total = $arr['total'];
		}
		return $total;
	}
	public static function getPageList($fields='*',$where='',$extra='',$page=0,$pagesizes=0,$tab='')
	{
		$sql = self::getsql($fields,$where,$extra,$page,$pagesizes,$tab);
		return self::selectsql($sql, "list");
	}
        public static function PageList($fields='*',$where='',$tab='',$extra='',$page=0,$pagesizes=0)
	{
		$sql = self::getsql($fields,$where,$extra,$page,$pagesizes,$tab);
		return self::selectsql($sql, "list");
	}
	public static function changeArrKey($arrlist,$getkey)
	{///从rs->fetchAll()获取数组后，把数组中的某个键值设置为特定的key
		$arrValue = array();
		if($arrlist)
		{
			foreach($arrlist as $key=>$value)
			{
				$newKey = $value[$getkey];
				$arrValue[$newKey] = $value;
			}
		}
		return $arrValue;
	}
	public static function getip()
	{
            $ip = '127.0.0.1';
		//return $_SERVER["REMOTE_ADDR"];
		if (!empty($_SERVER['HTTP_CLIENT_IP']))
		{
			$ip=$_SERVER['HTTP_CLIENT_IP'];
		}
		elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
		//to check ip is pass from proxy
		{
			$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
		}
		else
		{
			if(isset($_SERVER['REMOTE_ADDR']))
			{
				$ip=$_SERVER['REMOTE_ADDR'];
			}
			
		}
		return $ip;
	}
        
	/**
	* 开启事务
	*/
	public static function trans_begin($val=1)
	{
		if($val==1)
		{
			self::setdbw();
			self::$dbw->beginTransaction();//开启事务处理   
		}

	}

	/**
	* 提交事务
	*/
	public static function trans_commit($val=1)
	{
		if($val==1)
		{
			self::setdbw();
			self::$dbw->commit();//交易成功就提交
			self::$dbw->setAttribute(PDO::ATTR_AUTOCOMMIT, 1);
		}

	}

	/**
	* 回滚事务
	*/
	public static function trans_rollback($val=1)
	{
		if($val==1)
		{
			self::setdbw();
			self::$dbw->rollBack();
			self::$dbw->setAttribute(PDO::ATTR_AUTOCOMMIT, 1);
		}

	}
	public static function writejsonconfig($array,$name,$folder = '')
	{
		$json = json_encode($array, 256);
		$filename = ROOT."/config/".$folder.$name.".php";
		$str = '<?php return \''.$json.'\'; ?>';
		file_put_contents($filename, $str);
	}
        
//        public function __destruct() 
//        {
//            DBData::printtxt("执行完了");
//        }

	public static function changestrutf8($str,$lx=1)
	{
		$str=iconv("GB2312","UTF-8//IGNORE",$str) ;
		if($lx==1)
		{
			$str=trim($str);
		}
		
		return $str;
	}
	public static function changestrgb2312($str,$lx=1)
	{
		$str=iconv("UTF-8","gbk",$str) ;
		if($lx==1)
		{
			$str=trim($str);
		}
		return $str;
	}

	static public function fclass()
	{
		$errArr = debug_backtrace();
		var_dump($errArr);
	}
}